package com.weds.edwx.job;

import com.weds.core.utils.DateUtils;
import com.weds.edpf.core.constant.ScmParams;
import com.weds.edwx.entity.EdDineMealSettingEntity;
import com.weds.edwx.entity.EdDineOrderEntity;
import com.weds.edwx.entity.EdDineOrderInfoEntity;
import com.weds.edwx.service.EdDineMealSettingService;
import com.weds.edwx.service.EdDineOrderInfoService;
import com.weds.edwx.service.EdDineOrderService;
import com.weds.edwx.service.EdDineSettingService;
import com.weds.etl.base.SchedulerJob;
import com.weds.web.comm.entity.CommProcEntity;
import com.weds.web.comm.service.CommProcService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.PersistJobDataAfterExecution;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class EdDineOrderSchedulerJob extends SchedulerJob {
    @Autowired
    private EdDineMealSettingService edDineMealSettingService;
    @Autowired
    private EdDineOrderService edDineOrderService;
    @Autowired
    private ScmParams scmParams;
    @Autowired
    private CommProcService commProcService;
    @Autowired
    private EdDineOrderInfoService edDineOrderInfoService;

    private Logger log = LogManager.getLogger();
    @Override
    @Transactional
    public void execute(JobExecutionContext context) throws JobExecutionException {
        //取出所有餐别的截止订餐时间
        List<EdDineMealSettingEntity> list = edDineMealSettingService.selectListByEntity(new EdDineMealSettingEntity());
        try{
            SimpleDateFormat simdate1=new SimpleDateFormat("HH:mm");
            for(int i=0;i<list.size();i++){
                EdDineMealSettingEntity edDineMealSettingEntity = list.get(i);
                String nowStr = DateUtils.formatDate(new Date(),"HH:mm");
                //到了订餐截止时间
                //或 （订餐已经截止且 就餐时间还未截止，可支付一些还未支付的）
                if(edDineMealSettingEntity.getOrderEnd().equals(DateUtils.formatDate(new Date(),"HH:mm"))
                        || (
                        simdate1.parse(nowStr).compareTo(simdate1.parse(edDineMealSettingEntity.getOrderEnd())) >0
                                        &&
                                simdate1.parse(edDineMealSettingEntity.getRepastEnd()).compareTo(simdate1.parse(nowStr))>0)){
                    System.out.println("开始自动扣费");
                    EdDineOrderEntity edDineOrderEntity = new EdDineOrderEntity();
                    edDineOrderEntity.setPlaceId(edDineMealSettingEntity.getPlaceId());
                    edDineOrderEntity.setMealId(edDineMealSettingEntity.getMealId());
                    edDineOrderEntity.setOrderDate(DateUtils.formatDate(new Date(),"yyyy-MM-dd"));
                    List<EdDineOrderEntity> notPayList = edDineOrderService.selectOrderListNotPay(edDineOrderEntity);
                    for(int j=0;j<notPayList.size();j++){
                        System.out.println("开始自动扣费2");
                        EdDineOrderEntity payOrder = notPayList.get(j);
                        EdDineOrderInfoEntity order = new EdDineOrderInfoEntity();
                        // 消费扣费接口
                        CommProcEntity commProcEntity = new CommProcEntity();
                        commProcEntity.setProcName("link_update_dcxf");
                        List<Object> list1 = new ArrayList<>();
                        list1.add(Integer.parseInt(payOrder.getUserSerial()));
                        list1.add(DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
                        list1.add(payOrder.getPlaceId());
                        list1.add(payOrder.getOrderPrice().setScale(2, BigDecimal.ROUND_HALF_UP));
                        list1.add(scmParams.getChargeback());
                        list1.add(payOrder.getSubOrderId());
                        list1.add(payOrder.getMealName());
                        commProcEntity.setParams(list1);
                        List<List<Map>> resp = commProcService.loadProcData(commProcEntity);
                        String result = resp.get(0).get(0).get("").toString();
                        if (!"0".equals(result)) {
                            if ("1".equals(result)) {
                                order.setMealState("5");
                                order.setFailureReason("账户余额不足");
                            } else if ("2".equals(result)) {
                                order.setMealState("5");
                                order.setFailureReason("人员档案异常");
                            } else {
                                order.setMealState("5");
                                order.setFailureReason("未知原因");
                            }
                        }else{
                            System.out.println("支付成功，更改状态：："+payOrder.getSubOrderId());
                            order.setMealState("1");
                        }
                        order.setSubOrderId(payOrder.getSubOrderId());
                        edDineOrderInfoService.updateByPrimaryKeySelective(order);
                    }
                }
            }
        }catch (ParseException e){
            e.printStackTrace();
        }


        if("00:10".equals(DateUtils.formatDate(new Date(), "HH:mm"))){
            //如果到 00：00 分自动确认取餐
            EdDineOrderEntity edOrder = new EdDineOrderEntity();
            edOrder.setOrderDate(DateUtils.formatDate(DateUtils.addDays(new Date(),-1),"yyyy-MM-dds"));
            edOrder.setLtDate(new Date());
            int acount = edDineOrderService.updateOrderListNotCheck(edOrder);
            System.out.println("系统批量确认订餐信息：："+ acount);


        }
    }
}
